export default {
//  state表示的是数据（购物车数据，是数组结构）
  state: {
    cart: [
      {
        id: 1,
        title: '商品标题',
        img: '图片',
        price: 99.99,
        amount: 2,
        desc: '商品描述信息',
        checked: true
      }
    ]
  },

  mutations: {
    addToCart (state, payload) {
      const has = state.cart.some(prod => prod.id === payload.id)
      if (has) {
        state.cart = state.cart.map(prod => {
          if (prod.id === payload.id) {
            prod.amount += payload.amount
          }
          return prod
        })
      } else {
        state.cart = [
          ...state.cart,
          payload
        ]
      }
    },
    RemoveCartItem (state, payload) {
      state.cart = state.cart.filter(prod => {
        return prod.id !== payload
      })
    },
    changeCartItemAmount (state, payload) {
      state.cart = state.cart.map(prod => {
        if (prod.id === payload.id) {
          prod.amount = payload.amount
        }
        return prod
      })
    },
    toggleCartItem (state, payload) {
      state.cart = state.cart.map(prod => {
        if (prod.id === payload) {
          prod.checked = !prod.checked
        }
        return prod
      })
    },
    checkAllCartItem (state, payload) {
      state.cart = state.cart.map(prod => {
        prod.checked = payload
        return prod
      })
    }
  },
  actions: {},
  getters: { // 相当于组件的computed计算属性
    totalCount (state) {
      return state.cart.reduce((sum, curr) => {
        sum += curr.amount
        return sum
      }, 0)
    },
    checkedAll (state) {
      return state.cart.every(prod => prod.checked)
    },
    totalMoney (state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.price * prod.amount
        }
        return sum
      }, 0) * 100
    }
  }
}
